package com.demo2do.boyle.client.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.demo2do.boyle.client.cache.accessor.PersistentAccessor;
import com.demo2do.boyle.client.service.GeoService;
import com.demo2do.boyle.common.entity.geo.Geo;
import com.demo2do.boyle.common.entity.geo.Level;
import com.demo2do.core.persistence.GenericDaoSupport;
import com.demo2do.core.service.impl.GenericServiceImpl;

@Service("geoService")
public class GeoServiceImpl extends GenericServiceImpl<Geo> implements GeoService {
	
	@Autowired
	private GenericDaoSupport genericDaoSupport;
	
	@Autowired
	private PersistentAccessor persistentAccessor;
	
	/*
	 * (non-Javadoc)
	 * @see com.demo2do.boyle.client.service.GeoService#getGeo(java.lang.String)
	 */
	@SuppressWarnings("unchecked")
	public Geo getGeo(String code) {
		List<Geo> geos = genericDaoSupport.searchForList("FROM Geo geo WHERE geo.disabled = false AND geo.code = :code", "code", code);
		return geos.isEmpty() ? null : geos.get(0);
	}

	/*
	 * (non-Javadoc)
	 * @see com.demo2do.boyle.client.service.GeoService#getGeoByCode(java.lang.String)
	 */
	@SuppressWarnings("unchecked")
	public List<Geo> getCities(String code) {
		
		Map<String, Object> parameters = new HashMap<String, Object>();
		parameters.put("belongs", code);
		parameters.put("level", Level.CITY);
		return genericDaoSupport.searchForList("FROM Geo geo WHERE geo.disabled = false AND geo.belongs = :belongs AND geo.level = :level", parameters);
		
	}
	
	/*
	 * (non-Javadoc)
	 * @see com.demo2do.boyle.client.service.GeoService#getProvince()
	 */
	public List<Geo> getProvince() {
		Map<String, Object> provinceMap =  persistentAccessor.getEnabledProvinces();
		List<Geo> provinces = new ArrayList<Geo>();
		
		for(String key : provinceMap.keySet()) {
			provinces.add((Geo)provinceMap.get(key));
		}
		
		return provinces;
	}

}
